/*
 * Copyright (C) 2015-2021 Alibaba Group Holding Limited
 */

#include <stdio.h>
#include <stdlib.h>
#include <ulog/ulog.h>
#include <cx_debug.h>
#include <time.h>
#include "cx_hal.h"

#define TAG "cxutility"

void cx_util_utc_to_beijing(struct tm *time)
{
    time->tm_year += 1900;
    time->tm_mon += 1;
    uint8_t days = 0;
    if (time->tm_mon == 1 || time->tm_mon == 3 || time->tm_mon == 5 || time->tm_mon == 7 || time->tm_mon == 8 || time->tm_mon == 10 || time->tm_mon == 12)
    {
        days = 31;
    }
    else if (time->tm_mon == 4 || time->tm_mon == 6 || time->tm_mon == 9 || time->tm_mon == 11)
    {
        days = 30;
    }
    else if (time->tm_mon == 2)
    {
        if ((time->tm_year % 400 == 0) || ((time->tm_year % 4 == 0) && (time->tm_year % 100 != 0))) /* 判断平年还是闰年 */
        {
            days = 29;
        }
        else
        {
            days = 28;
        }
    }
    time->tm_hour += 8;      /* 北京时间比格林威治时间快8小时 */
    if (time->tm_hour >= 24) /* 跨天 */
    {
        time->tm_hour -= 24;
        time->tm_mday++;
        if (time->tm_mday > days) /* 跨月 */
        {
            time->tm_mday = 1;
            time->tm_mon++;
            if (time->tm_mon > 12) /* 跨年 */
            {
                time->tm_year++;
            }
        }
    }
}

struct tm *cx_util_localtime(void)
{
    time_t utime;
    struct tm *tm = NULL;

    time(&utime);
    tm = localtime(&utime);
    if (tm) {
        cx_util_utc_to_beijing(tm);
    }

    return tm;
}

void cx_util_localtime_print(char time_str[13])        // in format yyMMddhhmmss
{
    struct tm *tm = cx_util_localtime();

    memset(time_str, 0, 13);
    snprintf(time_str, 13, "%02d%02d%02d%02d%02d%02d", tm->tm_year - 2000, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
}
